package com.scu.phototabuser.ui.navitems;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.scu.phototabuser.Consts;
import com.scu.phototabuser.R;
import com.scu.phototabuser.data.source.local.User;
import com.scu.phototabuser.data.source.remote.Response;
import com.scu.phototabuser.http.OkHttp3Methods;
import com.scu.phototabuser.util.PreferenceUtil;
import com.scu.phototabuser.util.ToastUtil;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by tianfei on 2017/5/12.
 */

public class EditListActivity extends AppCompatActivity
        implements View.OnClickListener{

    public static final int RESULT_FOR_EDIT_USER_INFO = 0x1101;

    @BindView(R.id.tool_bar) Toolbar toolbar;
    @BindView(R.id.toolbar_btn_ok) TextView btn_ok;
    @BindView(R.id.toolbar_btn_cancel) TextView btn_cancel;

    @BindView(R.id.tv_uid) TextView tv_id;
    @BindView(R.id.edtv_name) EditText edtv_name;
    @BindView(R.id.edtv_sig) EditText edtv_sig;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_list_usrinfo);
        ButterKnife.bind(this);

        toolbar.setTitle("");
        setSupportActionBar(toolbar);

        btn_ok.setOnClickListener(this);
        btn_cancel.setOnClickListener(this);

        loadingUserInfo();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.toolbar_btn_ok:
                // FIXME: 2017/5/14

                if (TextUtils.isEmpty(edtv_name.getText().toString())){
                    ToastUtil.makeToast(EditListActivity.this,"User name cannot be null!");
                    break;
                }

                ProgressDialog dialog=new ProgressDialog(this,
                        R.style.TransparentProgressDialog);
                dialog.setMessage("uploading...");
                dialog.setIndeterminate(true);
                dialog.setCancelable(false);
                dialog.show();

                updateUserInfo();

                dialog.cancel();
                break;
            case R.id.toolbar_btn_cancel:
                onBackPressed();
                break;
            default:break;
        }
    }

    private void updateUserInfo(){
        Observable.create(new ObservableOnSubscribe<Boolean>() {
            @Override
            public void subscribe(@NonNull ObservableEmitter<Boolean> e) throws Exception {

                User user= Consts.mUser;

                Map<String,String> params=new HashMap<>();

                params.put("id",""+user.getId());

                String cname=edtv_name.getText().toString();
                String csig=edtv_sig.getText().toString();
                if (cname.equals(user.getName())
                        && csig.equals(user.getSignature())){
//                    ToastUtil.makeToast(EditListActivity.this,"");
                    e.onNext(false);
                }

                params.put("name",cname);
                params.put("sig",csig);

                String json= OkHttp3Methods.PostRequestWithToken(Consts.UpdateUserInfoURL,
                        params);

                Response response=new Gson().fromJson(json,Response.class);

                if (response.getCode() == 200){

                    //保存修改过的用户
                    Consts.mUser.setName(cname);
                    Consts.mUser.setSignature(csig);
                    e.onNext(true);
                }else {
                    e.onError(new RuntimeException(response.getMessage()));
                }
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Boolean>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {}
                    @Override
                    public void onNext(@NonNull Boolean b) {
                        if (b){
                            PreferenceUtil.saveUserInfo(Consts.mUser);
                            ToastUtil.makeToast(EditListActivity.this,getString(R.string.saved));
                            EditListActivity.this.setResult(RESULT_FOR_EDIT_USER_INFO);
                            EditListActivity.this.onBackPressed();
                        }else {
                            ToastUtil.makeToast(EditListActivity.this,getString(R.string.no_changes));
                            EditListActivity.this.onBackPressed();
                        }
                    }
                    @Override
                    public void onError(@NonNull Throwable e) {
                        ToastUtil.makeToast(EditListActivity.this,e.getMessage());
                    }
                    @Override
                    public void onComplete() {}
                });
    }

    private void loadingUserInfo() {
        User user= Consts.mUser;

        tv_id.setText(getString(R.string.empty)+user.getId());

        edtv_name.setText(user.getName());

        if (!TextUtils.isEmpty(user.getSignature())){
            edtv_sig.setText(user.getSignature());
        }
    }


  /*  class listItemInfo{
        private String showInfoLeft;
        private String editInfoRight;

        public String getShowInfoLeft() {
            return showInfoLeft;
        }

        public void setShowInfoLeft(String showInfoLeft) {
            this.showInfoLeft = showInfoLeft;
        }

        public String getEditInfoRight() {
            return editInfoRight;
        }

        public void setEditInfoRight(String editInfoRight) {
            this.editInfoRight = editInfoRight;
        }
    }

    class Adapter extends ArrayAdapter<listItemInfo>{
        private LayoutInflater mInflater;
        private List<listItemInfo> mList;

        Adapter(Context context, int resource, List<listItemInfo> objects) {
            super(context, resource, objects);
            mInflater=LayoutInflater.from(context);
            mList=objects;
        }

        @android.support.annotation.NonNull
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            final View v;
            if (convertView == null) {
                v = mInflater.inflate(R.layout.item_tv_edtv, parent, false);
            }else {
                v=convertView;
            }

            ((TextView)v.findViewById(R.id.tv_left)).setText(mList.get(position).getShowInfoLeft());
            EditText editText=(EditText)v.findViewById(R.id.edtv_right);

            String ed =mList.get(position).getEditInfoRight();
            if (TextUtils.isEmpty(ed)){
                editText.setHint(mList.get(position).getShowInfoLeft());
            }else {
                editText.setText(ed);
            }

            return v;
        }

    }
*/
}
